#!/usr/bin/ruby

require "#{File.dirname(__FILE__)}/../config/environment"

def insert_book(name_zh, name_en, new_t)
  b = BibleBook.find_by_name_en(name_en)
  b = BibleBook.create(
                       :name_zh => name_zh,
                       :name_en => name_en,
                       :new_testament => new_t
                      ) unless b
  return b.id
end

def insert_verse(book_id, chapter, verse, text_zh, text_en)
  v = BibleVerse.create(
                        :bible_book_id => book_id,
                        :chapter =>  chapter,
                        :verse =>  verse,
                        :text_zh =>  text_zh,
                        :text_en => text_en 
                       )
end

['old', 'new'].each do |testa|
  f = File.open("#{File.dirname(__FILE__)}/#{testa}-utf.txt")

  until f.eof?
    s = f.readline.strip

    # title
    if m = s.match(%{-- (.*) --})
      book_zh, book_en = m[1].chop.split('(')
      book_id = insert_book(book_zh, book_en, (testa == 'new'))
    elsif !s.empty?

      if m = s.match(/^(\d+):(\d+)\s+(.*)$/)
        # chinese
        chapter, verse, text_zh = m.to_a[1..-1]
      else
        # english
        text_en = s

        # insert_verses
        insert_verse(book_id, chapter.to_i, verse.to_i, text_zh, text_en)
        puts "#{book_zh} #{chapter}:#{verse}"
      end
    end
  end
  f.close
end
